package com.wujunshen.plugin.handler;

import org.elasticsearch.client.internal.node.NodeClient;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestRequest.Method;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.xcontent.XContentBuilder;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wujunshen
 */
@Slf4j
public class PrintPluginHandler extends BaseRestHandler {
    private static final String PRINT_NAME = "printPluginTest";

    @Inject
    public PrintPluginHandler(RestController restController) {
        super();

        // 注册
        restController.registerHandler(new Route(Method.GET, "/print-plugin"), this);
    }

    @Override
    public String getName() {
        return PRINT_NAME;
    }

    @Override
    public List<Route> routes() {
        return Collections.emptyList();
    }

    /**
     * 处理业务逻辑
     */
    @Override
    protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
        // 接收的参数
        log.info("params=={}", request.params());

        long startTime = System.currentTimeMillis();
        String name = request.param("name");
        long cost = System.currentTimeMillis() - startTime;

        // 返回内容，这里返回消耗时间 请求参数 插件名称
        return channel -> {
            XContentBuilder builder = channel.newBuilder();
            builder.startObject();
            builder.field("cost", cost);
            builder.field("name", name);
            builder.field("time", new Date());
            builder.field("pluginName", PRINT_NAME);
            builder.field("print", "this is print plugin test");
            builder.endObject();
            channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
        };
    }
}
